
#include "apue.h"
#include <setjmp.h>

static void f1(int, int, int, int);
static void f2(void);

static jmp_buf jmpbuffer;
static int globval; //全局变量

int main(void)
{
    int autoval;          //自动变量/局部变量
    register int regival; //寄存器变量
    volatile int volaval; //易失变量
    static int statval;   //静态变量

    globval = 1;
    autoval = 2;
    regival = 3;
    volaval = 4;
    statval = 5;

    if (setjmp(jmpbuffer) != 0)
    {
        printf("after longjmp: \n");
        printf("globval = %d, autoval = %d, regival = %d, volaval = %d, statval = %d\n",
               globval, autoval, regival, volaval, statval);
        exit(0);
    }
    /* 可以看到：
        自动变量/局部变量-auto-val 和 寄存器变量register-val
        全局变量global-val，静态变量static-val，在执行longjmp()跳转后，是不变的。-->不回滚
        易失变量volatile-val， --> 不回滚
    
    原则：
        1)放在寄存器中的，会回滚。
        2)放在存储器中的，不会回滚。
            优化后
                auto和register放在寄存器中，所以回滚;
                volatile global static存储在存储器中，不回滚。
            不优化
                这五个变量都放在存储器中(但是register是个例外，它在寄存器中，所以回滚)，所以不回滚
    */

    globval = 95;
    autoval = 96;
    regival = 97;
    volaval = 98;
    statval = 99;

    f1(autoval, regival, volaval, statval);
    exit(0);
}

static void f1(int i, int j, int k, int l)
{
    printf("in f1()\n");
    printf("globval = %d, autoval = %d, regival = %d, volaval = %d, statval = %d\n",
           globval, i, j, k, l);
    f2();
}
static void f2(void)
{
    longjmp(jmpbuffer, 1);
}
/*
lwh@lwh-HP-Notebook:~/ProjsGit/apue/APUE_my/07_Process_Env$ gcc testjmp.c -I ../include/    #不进行优化的编译
lwh@lwh-HP-Notebook:~/ProjsGit/apue/APUE_my/07_Process_Env$ ./a.out 
in f1()
globval = 95, autoval = 96, regival = 97, volaval = 98, statval = 99
after longjmp: 
globval = 95, autoval = 96, regival = 3, volaval = 98, statval = 99

lwh@lwh-HP-Notebook:~/ProjsGit/apue/APUE_my/07_Process_Env$ gcc -O testjmp.c -I ../include/  #优化编译
lwh@lwh-HP-Notebook:~/ProjsGit/apue/APUE_my/07_Process_Env$ ./a.out 
in f1()
globval = 95, autoval = 96, regival = 97, volaval = 98, statval = 99
after longjmp: 
globval = 95, autoval = 2, regival = 3, volaval = 98, statval = 99

*/